<template>
  <a-select
    showSearch
    :disabled="disabled"
    :getPopupContainer="getParentContainer"
    :placeholder="placeholder"
    v-model="selectedValue"
    style="width: 100%"
    :filterOption="filterOption"
    @change="handleAsyncChange"
    allowClear
  >
    <a-select-option v-for="d in options" :key="d.value" :value="d.value">{{ d.text }}</a-select-option>
  </a-select>

</template>

<script>
import {getAction} from '@api/manage'

export default {
  name: 'JSearchSelect',
  props: {
    disabled: Boolean,
    value: [String, Number],
    dict: String,
    placeholder: {
      type: String,
      default: '请选择',
      required: false
    },
    popContainer: {
      type: String,
      default: '',
      required: false
    },
    pageSize: {
      type: Number,
      default: 10,
      required: false
    }
  },
  data() {
    return {
      selectedValue: undefined,
      options: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if(this.dict){
          this.initDictData()
        }
        if (val) {
          this.selectedValue = val
        } else {
          this.selectedValue = undefined
        }
      }
    },
    dict: {
      handler(val) {
        if(val){
          this.initDictData()
        }
      },
      immediate: true
    },
  },
  methods: {
    initDictData() {
      getAction(`/api/erp/dict/getDictItems/${this.dict}`, {pageSize: this.pageSize,pageNo:10, keyword: ''}).then(res => {
        if (res.success) {
          this.options = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleAsyncChange(value) {
      this.selectedValue = value
      this.$emit('change', this.selectedValue)
    },
    getParentContainer(node) {
      if (!this.popContainer) {
        return node.parentNode
      } else {
        return document.querySelector(this.popContainer)
      }
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style scoped></style>
